package com.bosssoft.g1.gateway.aspect;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.bosssoft.g1.common.util.CommonResponseUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class SentinelAspect {

    @Around("execution(* com.bosssoft.g1.gateway.controller..*(..))")
    public Object sentinelProtection(ProceedingJoinPoint joinPoint) throws Throwable {
        Entry flowEntry = null;
        Entry degradeEntry = null;
        try {
            // 尝试进入限流资源
            flowEntry = SphU.entry("GLOBAL_LIMIT_RESOURCE");
            // 尝试进入熔断资源
            degradeEntry = SphU.entry("GLOBAL_CIRCUIT_BREAKER");
            // 执行目标方法
            return joinPoint.proceed();
        } catch (BlockException ex) {
            if (ex instanceof DegradeException) {
                // 打印熔断信息
                System.out.println("熔断 by Sentinel: " + ex.getClass().getSimpleName());
                return CommonResponseUtils.failed("Service has been degraded: " + ex.getClass().getSimpleName());
            }
            // 处理其他被限流的情况
            System.out.println("限流 by Sentinel: " + ex.getClass().getSimpleName());
            return CommonResponseUtils.failed("Blocked by Sentinel: " + ex.getClass().getSimpleName());
        } finally {
            if (degradeEntry != null) {
                degradeEntry.exit();
            }
            if (flowEntry != null) {
                flowEntry.exit();
            }
        }
    }
}